package com.jyj;

import io.jsonwebtoken.*;

import javax.xml.bind.DatatypeConverter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @class: com.jyj.TokenUtil
 * @description: 根据jwt生产token和解析token
 * @author: jiangzengkui
 * @company: 教育家
 * @create: 2021-01-03 18:02
 */
public class TokenUtil {


    // 主题
    public static final String SUBJECT = "教育家toeken";

    // 秘钥
    public static final String SECRETKEY = "jiangzengkuidashuaige";

    // 过期时间  1000 * 60 * 60 * 24 * 7
    public static final long EXPIRE = 1000 * 60 * 60 * 24 * 7; //过期时间，毫秒，一周

    // 生成 JWT

    /**
     *创建把用户信息以map形式加载，输出加密后的toekn
     * @param map  要放入token里的内容 如user_id
     *            eg:
     *
     * @return
     */
    public static String creatToken(Map map) {

        if (map == null || map.size() == 0) {

            return null;
        }

        String token = Jwts.builder() //主题
                .setSubject(SUBJECT)
                .setClaims(map)//内容
                .setIssuedAt(new Date()) //token创建日期
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) //过期日期
                .signWith(SignatureAlgorithm.HS256, SECRETKEY).compact(); //加密方式

        return token;
    }

    /**
     * 解析token,得到加载的用户信息
     */
    public static Map<String, Object> parseToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(SECRETKEY))
                    .parseClaimsJws(token).getBody();
        } catch (SignatureException | MalformedJwtException e){
            System.out.println("token解析失败");
        } catch (ExpiredJwtException e) {
            System.out.println("token已过期");
        }
        return claims;
    }

    public static void main(String[] args) {
        Map<String, Object> map=new HashMap<>();
        map.put("user_id","1223");
        map.put("user_name","蒋增奎");
//eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMTIyMyIsInVzZXJfbmFtZSI6IuiSi-WinuWljiIsImV4cCI6MTYxMDI3NDM1MSwiaWF0IjoxNjA5NjY5NTUxfQ.c5qzfE57rbbfGwarGjcATp1HGQqAGV2FKrUaFAGsHYc

        String token=creatToken(map);
        System.out.println(token);

        Map<String, Object> user=parseToken(token);
        for(String key:user.keySet()){//keySet获取map集合key的集合  然后在遍历key即可
            String value = user.get(key).toString();//
            System.out.println("key:"+key+" vlaue:"+value);
        }
    }

}